//
//  PictureSelectorViewController.swift
//  01-图片加载
//
//  Created by gxiangzi on 15/9/11.
//  Copyright © 2015年 hqu. All rights reserved.
//

import UIKit

private let PictureSelectorCellID = "PictureSelectorCellID"
private let GXMaxPictureCount = 9

class PictureSelectorViewController: UICollectionViewController,PictureSelectorCellDelegate{

    private var currentIndex :Int = 0
    var pictures = [UIImage]()
    
    init()
    {
        let layout = UICollectionViewFlowLayout()
        super.init(collectionViewLayout: layout)
        
        layout.itemSize = CGSize(width: 80, height: 80)
        layout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
     collectionView?.backgroundColor = UIColor(white: 0.97, alpha: 1.0)
        self.collectionView!.registerClass(PictureSelectorCell.self, forCellWithReuseIdentifier: PictureSelectorCellID)

        // Do any additional setup after loading the view.
    }
    
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of items
        return pictures.count + (pictures.count == GXMaxPictureCount ? 0 : 1)
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PictureSelectorCellID, forIndexPath: indexPath) as! PictureSelectorCell
        
        cell.pictureDelegate = self
        
        cell.image = indexPath.item < pictures.count ? pictures[indexPath.item] : nil
        
        
        
        return cell
    }
    
    /// 选择照片
    /// Camera          相机
    /// PhotoLibrary    图片库 - 包含相册，包含通过 iTunes / Photo 同步的照片，同步的照片不允许在手机删除
    /// SavePhotosAlbum 相册 - 相机拍摄，应用程序保存的图片，可以删除
    override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        if !UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary) {
            // 如果PhotoLibrary不可用
            return
        }
        
        currentIndex = indexPath.item
        
        let vc = UIImagePickerController()
        vc.delegate = self
        
        presentViewController(vc, animated: true, completion: nil)
    }
    
   func  pictureSelectorCellClickRemoveButton(cell: PictureSelectorCell) {
        if let indexPath = collectionView?.indexPathForCell(cell) where indexPath.item < pictures.count
        {
            // 删除对应索引的图像
            pictures.removeAtIndex(indexPath.item)
            
            collectionView?.reloadData()
    }
    }

    
}

extension PictureSelectorViewController:UIImagePickerControllerDelegate, UINavigationControllerDelegate
{
    /// 选中照片的代理方法
    ///
    /// - parameter picker:      picker 选择控制器
    /// - parameter image:       选中的图片
    /// - parameter editingInfo: 编辑字典，在开发选择用户头像时，格外有用 vc.allowsEditing = true 一旦允许编辑，选中的图像会小
    /// 
    ///
    /// 一旦实现代理方法，就需要自己关闭控制器
    /// 凡是开发相册有关的应用，需要考虑内存问题
    /// UIImageJPEGRepresentation 会严重影响图片的质量
    /// 关于应用程序内存，UI的App 空的程序运行占用 20M 左右 一个cocos2dx空模板建立应用程序运行会占 70M 内存
    /// 一般消耗 在100 以内都是可以接受的
    /// 参考数据：在 5s 一次测试数据，一直 sdwebimage 加载网络图像
    /// 内存飙升到 500M 接收到第一次内存警告！内存释放后的结果120M，程序仍然能够正常运行
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        let scaleImage = image.scaleImageToWidth(300)
        
        if currentIndex < pictures.count {
            pictures[currentIndex] = scaleImage
        } else {
            
            pictures.append(image)
        }
        
        collectionView?.reloadData()
        dismissViewControllerAnimated(true, completion: nil)
    }
}

protocol PictureSelectorCellDelegate:NSObjectProtocol {
    
    /// 选中删除按钮 - collectionView / tableView Cell 一个视图会包含多个 cell，在定义代理方法的时候，一定要传 cell
    /// 通过 cell 的属性，控制器能够判断出点击的对象
    func pictureSelectorCellClickRemoveButton(cell: PictureSelectorCell)
    
}

class PictureSelectorCell : UICollectionViewCell {
    
    var image :UIImage? {
        didSet {
            
            if image != nil {
            pictureButton.setImage(image, forState: UIControlState.Normal)
            } else {
                // 显示默认的加号图片
                pictureButton.setImage(UIImage(named: "compose_pic_add"), forState: UIControlState.Normal)
            }
            removeButton.hidden = (image == nil)
        }
    }
    
   /// 定义代理
    weak var pictureDelegate: PictureSelectorCellDelegate?
    
    /// 点击删除按钮
    @objc private func clickRemove() {
      pictureDelegate?.pictureSelectorCellClickRemoveButton(self)
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
     // MARK: - 添加控件
    private func setupUI() {
        // 1.添加控件
        contentView.addSubview(pictureButton)
        contentView.addSubview(removeButton)
        
        // 2.设置布局
        pictureButton.frame = bounds
        removeButton.translatesAutoresizingMaskIntoConstraints = false
        
        let viewDict = ["btn":removeButton]
      contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[btn]-0-|", options: [], metrics: nil, views: viewDict))
    contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[btn]", options: [], metrics: nil, views: viewDict))
        
        
        // 添加监听方法
        removeButton.addTarget(self, action: "clickRemove", forControlEvents: .TouchUpInside)

        // 设置pictureButton 禁止交互
        pictureButton.userInteractionEnabled  = false
        
    }
    
     // MARK: - 懒加载控件
    private var pictureButton = UIButton(imageName: "compose_pic_add")
    private var removeButton = UIButton(imageName: "compose_photo_close")
}